<template>
  <ElMenu
    v-bind="attrs"
    ref="elMenu"
    :collapse="collapse"
    :router="routerMode"
    @select="onSelect"
  >
    <template v-for="menu of menus" :key="menu.path">
      <template v-if="menu.children.length">
        <MenuItemSub :menu="menu!" :MenuItemSub="MenuItemSub" />
      </template>
      <template v-else>
        <ElMenuItem :index="menu.path">
          <ElIcon v-if="menu.menuIcon">
            <component :is="menu.menuIcon"></component>
          </ElIcon>
          <span>
            {{ menu.title }}
          </span>
        </ElMenuItem>
      </template>
    </template>
  </ElMenu>
</template>
<script lang="ts" setup>
import type { RouteMetaResolveRaw } from "@/utils";
import MenuItemSub from "./MenuItemSub.vue";
import { useAttrs } from "vue";

const props = defineProps<{
  menus: RouteMetaResolveRaw[];
  menuFlatList: RouteMetaResolveRaw[];
  routerMode?: boolean;
  collapse?: boolean;
  autoClose?: boolean;
}>();

const elMenu = ref<{
  open: (index: string) => void;
  close: (index: string) => void;
}>();

const route = useRoute();

/** 原始attrs */
const attrsRaw = useAttrs();

/** 包装后的attrs */
const attrs = computed(() => {
  if (props.routerMode) {
    return {
      ...attrsRaw,
      defaultActive: route.path,
    };
  } else {
    return attrsRaw;
  }
});

defineExpose({
  open: (index: string) => elMenu.value?.open(index),
  close: (index: string) => elMenu.value?.close(index),
});

const getParentPathList = (
  path: string,
  menuFlatList: RouteMetaResolveRaw[],
  list: string[],
): string[] => {
  const target = menuFlatList.find((item) => item.path === path);
  if (target?.parentPath) {
    list.unshift(target.parentPath);
    return getParentPathList(target.parentPath, menuFlatList, list);
  } else {
    return list;
  }
};

const onSelect = (index: string) => {
  const { autoClose } = props;
  if (autoClose) {
    const { menuFlatList } = props;
    const pathList = getParentPathList(index, menuFlatList, [index]);
    menuFlatList.forEach((item) => {
      if (!pathList.includes(item.path)) {
        elMenu.value?.close(item.path);
      }
    });
  }
};
</script>
